package com.nbjtjc.safe.service.danger;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.common.bean.TASKTABLESTATUS;
import com.nbjtjc.safe.activiti.service.ActivitiService;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.MyCache;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.danger.*;
import com.nbjtjc.safe.mapper.safe.SafeDangerInspectTaskRecordMapper;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.model.danger.*;
import com.nbjtjc.safe.model.safe.SafeDangerInspectTaskRecord;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.service.sys.SysDeptService;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @auther guqianbin
 * @date 2018/4/12 9:06
 **/
@Service
public class DangerInspectPublicService {

    @Autowired
    private DangerInspectPublicMapper dangerInspectPublicMapper;

    @Autowired
    private DangerInspectMapper dangerInspectMapper;
    @Autowired
    private DangerInspectListPublicMapper dangerInspectListPublicMapper;

    @Autowired
    private DangerInspectListPublicService dangerInspectListPublicService;
    @Autowired
    private DangerInspectMemberMapper dangerInspectMemberMapper;

    @Autowired
    private SafeDangerInspectLabelMapper safeDangerInspectLabelMapper;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysFileMapper sysFileMapper;

    @Autowired
    private DangerReformReplyMapper dangerReformReplyMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private MyCache myCache;
    @Autowired
    HistoryService historyService;

    @Autowired
    private ActivitiService activitiService;

    @Autowired
    private SafeDangerInspectTaskRecordMapper taskRecordMapper;
    @Transactional(rollbackFor = Throwable.class)
    public Result add(DangerInspectPublic dangerInspectPublic) {
        Result result = new Result();
        DangerInspect dangerInspect = dangerInspectMapper.selectByPrimaryKey(dangerInspectPublic.getInspectId());
        dangerInspectPublic.setPublicDeptId(MyShiroUtils.getDeptId());
        dangerInspectPublic.setPublicCompanyId(MyShiroUtils.getCompanyId());
        dangerInspectPublic.setCreateTime(new Date());
        dangerInspectPublic.setInspectType(dangerInspect.getInspectType());
        dangerInspectPublic.setCreateUserId(MyShiroUtils.getSessionUserId());
        dangerInspectPublicMapper.insertSelective(dangerInspectPublic);
        addInspectList(dangerInspectPublic);
        addInspectMembers(dangerInspectPublic);
        result.setData(dangerInspectPublic);
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    public Result delete(DangerInspectPublic dangerInspectPublic) {
        Result result = new Result();
        DangerInspectPublic dangerInspectPublic1 = dangerInspectPublicMapper.selectByPrimaryKey(dangerInspectPublic);
        if (ObjectUtil.isNotNull(dangerInspectPublic1)) {
            if (ObjectUtil.isNotNull(dangerInspectPublic1.getProcessInstanceId())) {
                activitiService.deleteProcessInstance(
                        dangerInspectPublic1.getProcessInstanceId());
            }
        }
        dangerInspectPublicMapper.deleteByPrimaryKey(dangerInspectPublic);
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    public Result update(DangerInspectPublic dangerInspectPublic) {
        Result result = new Result();
        dangerInspectPublicMapper.updateByPrimaryKeySelective(dangerInspectPublic);
        dangerInspectMemberMapper.deleteByInspectPublicId(dangerInspectPublic.getId());
//        dangerInspectListPublicMapper.deleteByInspectPublicId(dangerInspectPublic.getId());
        addInspectMembers(dangerInspectPublic);
//        addInspectList(dangerInspectPublic);
        return result;
    }

    public Result find(DangerInspectPublic dangerInspectPublic) {
        Result result = new Result();
        if (CollectionUtil.isNotEmpty(dangerInspectPublic.getLabel().getLabels())) {
            result.setData(searchByLabels(dangerInspectPublic));
        } else {
            PageHelper.startPage(dangerInspectPublic.getPageCurrent()
                    , dangerInspectPublic.getPageSize());
            List<DangerInspectPublic> dangerInspectPublics = dangerInspectPublicMapper
                    .search(dangerInspectPublic, null);
            if (CollectionUtil.isEmpty(dangerInspectPublics)) {
                result.setData(new PageInfo<>());
            } else {
                result.setData(new PageInfo<>(dangerInspectPublics));
            }
        }
        //todo  关联状态
        return result;
    }

    public Result search(DangerInspectPublic dangerInspectPublic) {
        Result result = new Result();

        PageHelper.startPage(dangerInspectPublic.getPageCurrent()
                , dangerInspectPublic.getPageSize());
        List<DangerInspectPublic> dangerInspectPublics = dangerInspectPublicMapper
                .search(dangerInspectPublic, null);
        if (CollectionUtil.isEmpty(dangerInspectPublics)) {
            result.setData(new PageInfo<>());
        } else {
            result.setData(new PageInfo<>(dangerInspectPublics));
        }
        return result;
    }
    public Result findSimple(DangerInspectPublic dangerInspectPublic) {
        Result result = new Result();
        List<DangerInspectPublic> dangerInspectPublics = dangerInspectPublicMapper
                .select(dangerInspectPublic);
        result.setData(dangerInspectPublics);
        return result;
    }

    public List<DangerInspectPublic> summary(int year) {
        String yearStart = year + "-01-01";
        String yearEnd = year + "-12-31";
        Date startDate = DateUtil.parse(yearStart);
        Date endDate = DateUtil.parse(yearEnd);
        DangerInspectPublic dangerInspectPublic = new DangerInspectPublic();
        dangerInspectPublic.setStartDate(startDate);
        dangerInspectPublic.setEndDate(endDate);
        dangerInspectPublic.setPublicCompanyId(MyShiroUtils.getCompanyId());
        List<DangerInspectPublic> dangerInspectPublics = dangerInspectPublicMapper.search(dangerInspectPublic, null);
        return dangerInspectPublics;
    }


    public Result detailNew(DangerInspectPublic dangerInspectPublic){
        Result result = new Result();
        dangerInspectPublic = dangerInspectPublicMapper.getDetail(dangerInspectPublic);
        if(ObjectUtil.isNull(dangerInspectPublic)){
            result.setFalse("没有该检查单");
            return result;
        }
        dangerInspectPublic.setDangerInspectListPublicList(
                dangerInspectListPublicService.compareInspectListPicsAndTaskRecord(
                        dangerInspectPublic.getDangerInspectListPublicList()
                ));
        result.setData(dangerInspectPublic);
        return result;
    }

    public Result saveTaskTable(DangerInspectPublic dangerInspectPublic){
        Result result = new Result();
        dangerInspectPublicMapper.updateByPrimaryKeySelective(dangerInspectPublic);
        if(dangerInspectPublic.getStatus().equals(TASKTABLESTATUS.SAVE.getCode())){
            List<SafeDangerInspectTaskRecord> taskRecordList=new ArrayList<>();
            dangerInspectPublic.getDangerInspectListPublicList().forEach(listPublic -> {
                taskRecordList.add(listPublic.getTaskRecord());
                SafeDangerInspectTaskRecord taskRecord=listPublic.getTaskRecord();
                if(ObjectUtil.isNotNull(taskRecord)){
                    if(ObjectUtil.isNotNull(taskRecord.getId())){
                        taskRecordMapper.updateByPrimaryKeySelective(taskRecord);
                    }else{
                        taskRecordList.add(taskRecord);
                    }
                }
            });
            if(CollectionUtil.isNotEmpty(taskRecordList)){
                taskRecordMapper.insertList(taskRecordList);
            }
        }
        return result;
    }

    public Result detail(DangerInspectPublic dangerInspectPublic) {
        Result result = new Result();
        dangerInspectPublic = dangerInspectPublicMapper.getDetail(dangerInspectPublic);
        if (ObjectUtil.isNull(dangerInspectPublic)) {
            result.setFalse("没有该检查单");
            return result;
        }
        if (ObjectUtil.isNotNull(dangerInspectPublic)) {
            if (ObjectUtil.isNotNull(dangerInspectPublic.getTargetContractorUserId())) {
                dangerInspectPublic.setTargetContractorUserName(
                        sysUserMapper.findNameByUserId(dangerInspectPublic.getTargetContractorUserId()));
            }

        }
        if (ObjectUtil.isNotNull(dangerInspectPublic.getCheckUserId())) {
            dangerInspectPublic.setCheckUserName(myCache
                    .getUserName(dangerInspectPublic.getCheckUserId()));
        }
        compareDangerInspectList(dangerInspectPublic);
        compareReply(dangerInspectPublic);
        SysFile inspectAttach = new SysFile();
        inspectAttach.setContentType(Constant.SysFileType.DANGER_INSPECT_ATTACH.getValue());
        inspectAttach.setContentId(dangerInspectPublic.getId());
        List<SysFile> attachments = sysFileMapper.select(inspectAttach);
        dangerInspectPublic.setAttachments(attachments);

        if (CollectionUtil.isNotEmpty(dangerInspectPublic.getDangerInspectListPublicList())) {
            dangerInspectPublic.getDangerInspectListPublicList().forEach(dangerInspectListPublic -> {
                SysFile sysFile = new SysFile();
                sysFile.setContentType(Constant.SysFileType.DANGER_PIC.getValue());//隐患照片
                sysFile.setContentId(dangerInspectListPublic.getId());
                List<SysFile> dangerPics = sysFileMapper.select(sysFile);
                if (CollectionUtil.isNotEmpty(dangerPics)) {
                    dangerInspectListPublic.setDangerPics(dangerPics);
                }
                sysFile.setContentType(Constant.SysFileType.DANGER_REFORM_PIC.getValue());//整改后照片
                List<SysFile> changePics = sysFileMapper.select(sysFile);
                if (CollectionUtil.isNotEmpty(changePics)) {
                    dangerInspectListPublic.setChangePics(changePics);
                }
            });
        }
        result.setData(dangerInspectPublic);
        return result;
    }

    /**
     * 装配检查单的属性，装配当前整改任务所处状态,照片
     *
     * @param dangerInspectPublic
     */
    private void compareDangerInspectList(DangerInspectPublic dangerInspectPublic) {
        if (ObjectUtil.isNull(dangerInspectPublic)) {
            return;
        }
        if (CollectionUtil.isEmpty(dangerInspectPublic.getDangerInspectListPublicList())) {
            return;
        }
        dangerInspectPublic.getDangerInspectListPublicList().forEach(dangerInspectListPublic -> {
            if (ObjectUtil.isNotNull(dangerInspectListPublic.getApplyUserId())) {
                dangerInspectListPublic.setApplyUserName(
                        myCache.getUserName(dangerInspectListPublic.getApplyUserId()));
            }
        });
        dangerInspectListPublicService.compareDangerInspectListPicsAndoverTime(
                dangerInspectPublic.getDangerInspectListPublicList(),new HashMap<>());
    }

    private PageInfo searchByLabels(DangerInspectPublic dangerInspectPublic) {
        HashMap<Integer, Integer> dangerInspectPublicMap = new HashMap<>();
        SafeDangerInspectLabel label = dangerInspectPublic.getLabel();
        List<SafeDangerInspectLabel> safeDangerInspectLabels =
                safeDangerInspectLabelMapper.search(label, null);
        if (CollectionUtil.isEmpty(safeDangerInspectLabels)) {
            return new PageInfo<>(new ArrayList<DangerInspect>());
        }
        safeDangerInspectLabels.forEach(safeDangerInspectLabel -> {
            if (dangerInspectPublicMap.containsKey(safeDangerInspectLabel.getInspectId())) {
                dangerInspectPublicMap.put(safeDangerInspectLabel.getInspectId()
                        , dangerInspectPublicMap.get(safeDangerInspectLabel.getInspectId()) + 1);
            } else {
                dangerInspectPublicMap.put(safeDangerInspectLabel.getInspectId(), 1);
            }
        });
        List<Integer> validatorInspectIds = new ArrayList<>();
        dangerInspectPublicMap.entrySet().forEach(entry -> {
            if (entry.getValue().equals(label.getLabels().size())) {
                validatorInspectIds.add(entry.getKey());
            }
        });
        if (CollectionUtil.isEmpty(validatorInspectIds)) {
            return new PageInfo<>(new ArrayList<DangerInspect>());
        }
        PageHelper.startPage(dangerInspectPublic.getPageCurrent(), dangerInspectPublic.getPageSize());
        List<DangerInspectPublic> dangerInspectPublics = dangerInspectPublicMapper
                .search(dangerInspectPublic, validatorInspectIds);
        return new PageInfo<>(dangerInspectPublics);
    }

    /**
     * 插入对应的检查组成员
     *
     * @param dangerInspectPublic
     */
    private void addInspectMembers(DangerInspectPublic dangerInspectPublic) {
        if (CollectionUtil.isNotEmpty(dangerInspectPublic.getDangerInspectMembers())) {
            dangerInspectPublic.getDangerInspectMembers().forEach(dangerInspectMember -> {
                dangerInspectMember.setInspectTablePublicId(dangerInspectPublic.getId());
            });
            dangerInspectMemberMapper.insertList(dangerInspectPublic.getDangerInspectMembers());
        }
    }

    /**
     * 插入检查表对应的检查清单记录
     *
     * @param dangerInspectPublic
     */
    private void addInspectList(DangerInspectPublic dangerInspectPublic) {
        if (CollectionUtil.isNotEmpty(dangerInspectPublic.getDangerInspectListPublicList())) {
            dangerInspectPublic.getDangerInspectListPublicList().forEach(dangerInspectListPublic -> {
                dangerInspectListPublic.setInspectPublicId(dangerInspectPublic.getId());
                dangerInspectListPublic.setNeedChange(Constant.NeedChange.UNNEED_CHANGE.getValue());
                dangerInspectListPublic.setCreateTime(new Date());
            });
            dangerInspectListPublicMapper.insertList(dangerInspectPublic.getDangerInspectListPublicList());
        }
    }


    /**
     * 加载回执单
     *
     * @param dangerInspectPublic
     */
    private void compareReply(DangerInspectPublic dangerInspectPublic) {
        DangerReformReply dangerReformReply = new DangerReformReply();
        dangerReformReply.setDangerInspectPublicId(dangerInspectPublic.getId());
        List<DangerReformReply> dangerReformReplies = dangerReformReplyMapper.search(dangerReformReply);
        dangerInspectPublic.setDangerReformReplies(dangerReformReplies);
    }
}
